import React, { useState, useEffect } from 'react';
import { Layout, Menu } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { findMatchingKey, findTopLevelParent } from '@/core/menus';
import themeColors from '@/core/themeColors';
import { iconfontUrl } from '@/core/config';
import { createFromIconfontCN } from '@ant-design/icons';

const { Sider, Content } = Layout;
const { theme } = themeColors;

const MyIcon = createFromIconfontCN({
  scriptUrl: iconfontUrl, // 在 iconfont.cn 上生成
});

const LayoutWithSidebar = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [selectedMenuKeys, setSelectedMenuKeys] = useState([]);
  const [subMenus, setSubMenus] = useState([]);
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const path = location.pathname;
    setSubMenus(findTopLevelParent(path)?.children || []);
    setSelectedMenuKeys([findMatchingKey(path)]);
  }, [location]);

  const onClickMenuItem = (e) => {
    const { key } = e;
    navigate(key);
  };

  const mainContentStyle = {
    marginLeft: '200px',
    // minWidth: '1120px'
  };

  const siderStyle = {
    overflow: 'auto',
    height: '100vh',
    position: 'fixed',
    left: 0,
    top: '60px',
    paddingTop: '20px',
    bottom: 0,
  };

  return (
    <Layout className="sidebar">
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
        theme="light"
        style={siderStyle}
      >
        <Menu
          className="sidebar-menu"
          items={subMenus}
          selectedKeys={selectedMenuKeys}
          mode="inline"
          onClick={onClickMenuItem}
        />
      </Sider>
      <Content style={mainContentStyle}>
        <Outlet />
      </Content>
    </Layout>
  );
};

export default LayoutWithSidebar;
